package com.vkmessenger.gui.components;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.*;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TextView;
import com.vkmessenger.R;
import com.vkmessenger.core.media.MediaPlayerFactory;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 23.06.12
 * Time: 14:53
 */
public class AudioPanel extends TableLayout {
    private static final Logger logger = Logger.getLogger(AudioPanel.class.getName());
    public final ImageView playStop, loaded, played, pos, playback;
    public final FrameLayout playbackHolder;
    private final int ctrlSZ;
    private volatile boolean sliderLocked = false;

    public volatile MediaPlayer player;
    public volatile String url;

    public final AtomicInteger state = new AtomicInteger(0);
    public static final int NOT_READY = 0, GETTING_READY = 1, READY = 2, PLAYING = 3, PAUSE = 4, DOWN = 5;

    public AudioPanel(Context context) {
        this(context, null);
    }

    public AudioPanel(Context context, AttributeSet attrs) {
        super(context, attrs);
        ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.audio_panel, this);
        playStop = (ImageView) findViewById(R.id.img_play_stop);
        loaded = (ImageView) findViewById(R.id.img_playback_loaded);
        played = (ImageView) findViewById(R.id.img_playback_played);
        playback = (ImageView) findViewById(R.id.img_play_stop);
        pos = (ImageView) findViewById(R.id.img_playback_pos);
        playbackHolder = (FrameLayout) findViewById(R.id.playback_holder);

        int sz = playStop.getDrawable().getIntrinsicHeight() / 4;
        setPadding(sz, sz, sz, sz);
        playStop.setPadding(0, 0, sz / 2, 0);

        ctrlSZ = pos.getDrawable().getIntrinsicWidth() / 2;

        playbackHolder.setPadding(ctrlSZ, 0, ctrlSZ, 0);

        reset();
        playStop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                int s = state.get();
                switch (s) {
                    case GETTING_READY:
                        return;
                    case NOT_READY:
                        if (state.compareAndSet(s, GETTING_READY)) prepare();
                        return;
                    case PAUSE:
                        if (state.compareAndSet(s, PLAYING)) {
                            player.start();
                            playStop.setSelected(false);
                        }
                        return;
                    case PLAYING:
                        if (state.compareAndSet(s, PAUSE)) {
                            playStop.setSelected(true);
                            player.pause();
                        }
                        return;
                }
            }
        }

        );

        findViewById(R.id.playback_clickable).setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (player != null) {
                    int s = state.get();
                    if(s != PAUSE && s != PLAYING) return true;

                    int padding = (int) motionEvent.getX() - ctrlSZ;
                    int barLength = view.getWidth() - 2 * ctrlSZ;

                    if (padding < 0) padding = 0;
                    if (padding > barLength) padding = barLength;

                    pos.setPadding(padding, 0, 0, 0);

                    sliderLocked = true;

                    if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        int duration = player.getDuration();
                        int ms = (int) ((float) padding / barLength * duration);
                        player.seekTo(ms);
                    }
                }
                return true;
            }
        }

        );

    }

    private void reset() {
        playStop.setSelected(true);
        pos.setPadding(0, 0, 0, 0);
        played.setLayoutParams(new FrameLayout.LayoutParams(0,
                ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER_VERTICAL));
        loaded.setLayoutParams(new FrameLayout.LayoutParams(0,
                ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER_VERTICAL));
    }

    public void wireWithSong(String url, String author, String name) {
        ((TextView) findViewById(R.id.text_song_author)).setText(author);
        ((TextView) findViewById(R.id.text_song_name)).setText(name);
        this.url = (url);
    }

    private void prepare() {
        final MediaPlayer mp = MediaPlayerFactory.retrieveMediaPlayer(this);
        player = mp;

        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
                playStop.setSelected(false);
                sliderLocked = false;
                state.set(PLAYING);
            }
        });

        mp.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
                int w = playbackHolder.getWidth() - 2 * ctrlSZ;

                if (player.isPlaying()) {
                    int duration = mediaPlayer.getDuration();
                    int playPercent = duration == 0 ? 0 : 100 * mediaPlayer.getCurrentPosition() / duration;
                    if(!sliderLocked) pos.setPadding(w * playPercent / 100, 0, 0, 0);
                    played.setLayoutParams(new FrameLayout.LayoutParams(w * playPercent / 100,
                            ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER_VERTICAL));
                }
                loaded.setLayoutParams(new FrameLayout.LayoutParams(w * i / 100,
                        ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER_VERTICAL));
            }
        });

        mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            public void onSeekComplete(MediaPlayer mediaPlayer) {
                sliderLocked = false;
            }
        });

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (mp.getCurrentPosition() != 0) {
                    playStop.setSelected(true);
                    state.set(PAUSE);
                }
            }
        });


        try {
            mp.setDataSource(url);
        } catch (IOException e) {
            System.out.println("NOT SET DATA SRC");
        }
        mp.prepareAsync();
    }

    public void releaseMediaPlayer() {
//        while (true) {
//            int s = state.get();
//            if (s != GETTING_READY && state.compareAndSet(s, DOWN)) {
//                break;
//            } else {
//                try {
//                    Thread.sleep(50);
//                } catch (InterruptedException e) {}
//            }
//        }
        player.setOnPreparedListener(null);
        player.setOnBufferingUpdateListener(null);
        player.setOnSeekCompleteListener(null);
        player.setOnCompletionListener(null);
        player.reset();
        player = null;
        state.set(NOT_READY);
        reset();
    }
}
